package com.xneure.enging;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xneure.code.msg.MessageListener;
import com.xneure.code.msg.MsgManage;

public class WebContext implements Context {
	private MsgManage msgManage = new MsgManage();
	
	@Override
	public boolean isValid() {
		return (System.currentTimeMillis() - getSession().getLastAccessedTime()) < getSession()
				.getMaxInactiveInterval();
	}

	@Override
	public void checkValid() {
		if(isValid()==false){
			getSession().invalidate();
		}
	}

	public static HttpServletRequest getRequest() {
		return getServlet().getRequest();
	}

	private static ServletRequestAttributes getServlet() {
		return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
	}

	public static HttpSession getSession() {
		return getRequest().getSession();
	}
	
	public static HttpServletResponse getResponse(){
		return getServlet().getResponse();
	}

	@Override
	public String getId() {
		return getSession().getId();
	}

	@Override
	public <T> void registerListen(MessageListener<? super T> msg) {
		msgManage.registerListen(msg);
	}

	@Override
	public <T> void registerListen(Class<T> c, MessageListener<? super T> msg) {
		msgManage.registerListen(c, msg);
	}

	@Override
	public <T> void sendMessage(T msg, Enum<?> action) {
		msgManage.sendMessage(msg,action);
	}
	
}
